﻿#region Copyright and License
/*==============================================================================
 *  Copyright (c) www.51mvc.com Corporation.  All rights reserved.
 * ===============================================================================
 * This code and information is provided "as is" without warranty of any kind,
 * either expressed or implied, including but not limited to the implied warranties
 * of merchantability and fitness for a particular purpose.
 * ===============================================================================
 * Licensed under the GNU General Public License (GPL) v2
 * http://www.51mvc.com/
 * Create By 小鱼(Leven)  - http://leven.com.cn
 * ==============================================================================*/
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using Infancy.Core.Validation;
using Infancy.Core.Reflection;

namespace Infancy.Core.Entities {
    /// <summary>
    /// 对验证实体的基本实现,大部分可验证实体应直接或者间接继承该类
    /// </summary>
    /// <typeparam name="TEntity"></typeparam>
    public abstract class ValidateEntityBase<TEntity> :
        EntityBase<TEntity>, IValidateEntity
        where TEntity : IEntity {
        #region IValidateEntity Members

        /// <summary>
        /// 验证该实体
        /// </summary>
        /// <returns></returns>
        public virtual ValidatedResult Validate() {
            bool result = true;
            Dictionary<string, string> errors = new Dictionary<string, string>();
            FastPropertyInfo[] properties = GetProperties();
            foreach (FastPropertyInfo p in properties) {
                ValidateAttributeBase[] attributes = p.Property.GetCustomAttributes(typeof(ValidateAttributeBase), true) as ValidateAttributeBase[];
                if (attributes.Length > 0) {
                    foreach (ValidateAttributeBase item in attributes) {
                        ValidatedResult vr = item.Execute(
                            new ValidateContext(p.Property.Name, p.Get(this)));
                        result = vr.Result && result;
                        if (!result) {
                            foreach (var kp in vr.Errors) {
                                errors.Add(kp.Key, kp.Value);
                            }
                        }
                    }
                }
            }
            return new ValidatedResult(result, errors);
        }

        #endregion
    }
}
